<?php

namespace app\models;

use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\data\Pagination;
use yii\db\ActiveRecord;

/**
 * 项目开发 表关联 标准
 * User 关联 status == 10|20 的用户（关联正常、停用的用户）
 * Product 只关联 status == 10 的产品（不关联停用的产品，除了产品列表）
 * Role 只关联 status == 10 的角色（登录的时候，只拉取启用的用户和启用的角色权限）
 * @author ZhangYuan 574368565@qq.com
 * @time 2021/2/18 15:23
 */
class BaseModel extends ActiveRecord
{
    public $operation_log;

    public function behaviors()
    {
        return [
            'blameable' => [
                'class' => BlameableBehavior::class, //save前变更created_by、updated_by
            ],
            'timestamp' => [
                'class' => TimestampBehavior::class, //save前变更created_at、updated_at
            ],
        ];
    }

    public static function listPage($where = [], $select = '', $orderBy = 'id desc', $page = 1, $pageSize = 20, $joinWith = [], $group = '', $isArray = false)
    {
        $model = new static();
        if (!$select) {
            $select = $model->getOldAttributes();
        }
        $query = self::find();

        if ($joinWith) {
            if (is_array($joinWith) && in_array('RIGHT JOIN', $joinWith)) {
                $query->joinWith($joinWith[0], $joinWith[1], $joinWith[2]);
            } else {
                $query->joinWith($joinWith);
            }
        }

        if (is_array($where)) {
            foreach ($where as $key => $val) {
                if (!is_integer($key)) {
                    $query->andWhere($where);
                    break;
                } else {
                    $query->andWhere($val);
                }
            }
        } else {
            $query->where($where);
        }

        // 判断是否分页
        if ($page === null && $pageSize === null) {
            $offset = null;
            $limit = null;
            $total = null;
        } else {
            $pagination = new Pagination([
                'defaultPageSize' => $pageSize,
                'totalCount' => $query->groupBy($group)->count(),
            ]);
            $pagination->setPage((int)$page - 1);

            $offset = $pagination->offset;
            $limit = $pagination->limit;
            $total = $pagination->totalCount;
        }

        $list = $query->select($select)->orderBy($orderBy)
            ->offset($offset)
            ->limit($limit)
            ->asArray($isArray)
            ->groupBy($group)
            ->all();
        $total = $total ?: count($list);

        return ['code' => 0, 'msg' => '', 'count' => $total, 'data' => $list];
    }

    /**
     * save()前向model实例化一个操作日志，并记录原数据
     * @method beforeSave
     * @param bool $insert
     * @return bool
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/2/24 10:45
     */
    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) return false;
        $operation_log = new \app\services\OperationLog();
        $operation_log->orgin = $this->getOldAttributes();
        $operation_log->data = $this->getAttributes();
        $this->operation_log = $operation_log;
        return true;
    }

    /**
     * save()后向model中的操作日志OBJ，添加变更后数据和变化数据
     * @method afterSave
     * @param bool $insert
     * @param array $changedAttributes
     * @return bool|void
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/2/24 10:46
     */
    public function afterSave($insert, $changedAttributes)
    {
        //更新现有数据
        $this->operation_log->data = $this->getAttributes();
        //重新拼接变动数据
        if ($this->operation_log->orgin && $this->operation_log->data) {
            $change = $changedAttributes;
            foreach ($change as $attribute => &$val) {
                $val = $this->operation_log->orgin[$attribute] . ' -> ' . $this->operation_log->data[$attribute];
            }
            $this->operation_log->change = $change;
        }

        if (!parent::afterSave($insert, $changedAttributes)) return false;
        return true;
    }
}
